package czk.concrent.synControl.practice;

import java.util.concurrent.locks.LockSupport;

/**
 *
 * @Author:ChenZhangKun
 * @Date: 2021/3/24 16:43
 */
public class LockSupportDemo {
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) {
        UnPark unPark = new UnPark(5);
        t1 = new Thread(() -> {
            unPark.print("A", t2);
        });
        t2 = new Thread(() -> {
            unPark.print("B", t3);
        });
        t3 = new Thread(() -> {
            unPark.print("C", t1);
        });
        t1.start();
        t2.start();
        t3.start();
        // 释放
        LockSupport.unpark(t1);
    }

}

class UnPark {
    /**
     * 循环次数
     */
    private int loopNum;

    public UnPark(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String content, Thread next) {
        //
        for (int i = 0; i < loopNum; i++) {
            // 首先阻塞自己
            LockSupport.park();
            // 打印
            System.out.print(content);
            // 解锁下一个
            LockSupport.unpark(next);
        }
    }
}
